package org.amuthu.expression.binary;

import org.amuthu.expression.AbstractExpression;
import org.amuthu.expression.Expression;

/**
 * Abstract base class for all expressions requiring two arguments.
 */
abstract public class BinaryExpression extends AbstractExpression
{
   /**
    * Create a new binary expression with the given left and right
    * arguments.
    *
    * @param	left	the left argument
    * @param	right	the right argument
    */
   public BinaryExpression(Expression left,
                           Expression right)
   {
      super(new Expression[]
              {
                 left, right
              });
      assert left != null && right != null;
   }

   /**
    * Return the number of children required in a binary expression.
    * This will always evaluate to <code>2</code>.
    *
    * @return	<code>2</code>
    */
   @Override
   public int getChildCount()
   {
      return 2;
   }

   /**
    * Helper method to convert the given expression to a string.
    * Given an operator such as <code>+</code>, <code>-</code> etc
    * it will return <code>arg1 operator arg2</code>. It will insert
    * parentheses as needed.
    *
    * @param	operator	the binary operator
    * @return	the string representation
    */
   protected String toString(String operator)
   {
      String string = "";

      string = toString(getChild(0));
      string += operator;
      string += toString(getChild(1));

      return string;
   }

   protected String toString(Expression child)
   {
      String string = "(null)";

      if (child != null)
      {
         if (child.getChildCount() < 2)
         {
            string = child.toString();
         }
         else
         {
            string = "(" + child.toString() + ")";
         }
      }

      return string;
   }

}
